/**
 * JAVACC DEMO 1.0
 * @copy right apache company All rights reserved. 
 * @Package com.apache.rpc.server.threads  
 */
package com.apache.rpc.server.threads;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.apache.cache.util.Validator;
import com.apache.rpc.server.impl.ClientSocketLisener;
import com.apache.rpc.util.DesUtils;
import com.apache.rpc.util.XMLMapParse;

/**
 * description:  服务端接收客户端信息
 * @author Hou Dayu 创建时间：2015-1-9  
 * @Copyright(c)2014:
 */
public class ReceiveClientSocketJob implements ISchedulerJob {

	private Socket socket;
	private Logger log = Logger.getLogger(ReceiveClientSocketJob.class);
	private boolean isEncrypt;
	private String key;

	public ReceiveClientSocketJob(Socket socket, boolean isEncrypt, String key) {
		this.socket = socket;
		this.isEncrypt = isEncrypt;
		this.key = key;
	}

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see java.lang.Runnable#run()  
	 */
	public boolean execute() {
		String result = "";
		try {
			String strMsg = "";
			if (socket != null && socket.isConnected() && !socket.isClosed()) {
				byte[] data = new byte[102400];
				InputStream in = new BufferedInputStream(socket.getInputStream());
				in.read(data);
				strMsg = new String(data, "UTF-8");
				strMsg = strMsg.trim();
				result = getClientsend(strMsg);

				byte[] data_byte_arr = result.getBytes("UTF-8");

				int data_len = data_byte_arr.length;

				byte[] data_byte_len = Int2BytesLH(data_len);

				OutputStream os = socket.getOutputStream();

				//发送实际数据长度
				os.write(data_byte_len, 0, data_byte_len.length);
				log.debug("data_byte_len_length=" + data_len);
				//发送实际数据内容
				os.write(data_byte_arr, 0, data_byte_arr.length);
				log.debug("data_byte_arr=" + result);
				os.flush();
			}
		} catch (Exception e) {
			try {
				socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			ClientSocketLisener.getinstance().removeSocket(key);
			return false;
		}
		return true;
	}

	private String getClientsend(String strMsg) {
		String result = "";
		if (!Validator.isNull(strMsg)) {
			log.debug("接收到客户端的消息为:" + strMsg);
			String params = strMsg;
			if (isEncrypt) {
				params = DesUtils.getInstance().decrypt(strMsg);
			}
			Map<String, Object> headMap = new HashMap<String, Object>();
			if (params.startsWith("[{")) {
				params = XMLMapParse.instance().jsonToXMl(params);
			}
			if (params.startsWith("<?")) {
				XMLMapParse.instance().xmlGetDataToHead(params, headMap);
				result = ClientSocketLisener.getinstance().doService(strMsg, headMap.get("ParamType").toString(),
						isEncrypt);
			}
		}
		return result;
	}

	/**
	 * description:  将int转成字节数组
	 * @param n
	 * @return   
	 */
	private byte[] Int2BytesLH(int n) {
		byte[] b = new byte[4];
		b[0] = (byte) (n & 0xff);
		b[1] = (byte) (n >> 8 & 0xff);
		b[2] = (byte) (n >> 16 & 0xff);
		b[3] = (byte) (n >> 24 & 0xff);
		return b;
	}
}
